package cn.xerllent.wxtp.handler;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.service.WxAdminService;
import cn.xerllent.wxtp.service.WxCorpService;
import cn.xerllent.wxtp.service.WxDepartmentService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.WxCpTpPermanentCodeInfo;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

/**
 * @author sxh
 * 企业创建授权处理
 */
@Component
@Slf4j
public class AuthCreateHandler extends AbstractHandler {

	private final WxCorpService wxCorpService;
	private final WxAdminService wxAdminService;
	private final WxDepartmentService wxDepartmentService;

	@Autowired
	@Qualifier("singleThreadExecutor")
	private ExecutorService singleThreadExecutor;

	public AuthCreateHandler(WxCorpService wxCorpService,WxAdminService wxAdminService,WxDepartmentService wxDepartmentService) {
		super();
		this.wxCorpService = wxCorpService;
		this.wxAdminService = wxAdminService;
		this.wxDepartmentService = wxDepartmentService;
	}


	@Override
	public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage,
			Map<String, Object> context,
			WxCpTpService wxCpTpService,
			WxSessionManager sessionManager) {
		try {
			String suiteId = wxMessage.getSuiteId();
			String authCode = wxMessage.getAuthCode();
			String timeStamp = wxMessage.getTimeStamp();
			WxCpTpPermanentCodeInfo permanentCode = wxCpTpService.getPermanentCodeInfo(authCode);

			//先查是否存在
			WxCorp wxCorp = wxCorpService.getOne(new LambdaQueryWrapper<WxCorp>().eq(WxCorp::getCorpId, permanentCode.getAuthCorpInfo().getCorpId()).eq(WxCorp::getSuiteId, suiteId));
			if(wxCorp==null) {
				wxCorp = new WxCorp();
			}

			wxCorp.setCorpId(permanentCode.getAuthCorpInfo().getCorpId())
			.setSuiteId(suiteId)
			.setAgentId(permanentCode.getAuthInfo().getAgents().get(0).getAgentId())
			.setCorpName(permanentCode.getAuthCorpInfo().getCorpName())
			.setCorpFullName(permanentCode.getAuthCorpInfo().getCorpFullName())
			.setPermanentCode(permanentCode.getPermanentCode())
			.setSubjectType(permanentCode.getAuthCorpInfo().getSubjectType())
			.setCreatetime(LocalDateTime.now())
			//.setVerifiedEndTime(new Date(permanentCode.getAuthCorpInfo().getVerifiedEndTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime())
			.setWxpackage(permanentCode.toJson())
			.setStatus(1);

			wxCorpService.saveOrUpdate(wxCorp);

			final WxCorp corp = wxCorp;

			// TODO: 后续应用初始化数据操作，审批模板复制...,异步线程执行
			singleThreadExecutor.execute(new Runnable() {

				@Override
				public void run() {
					//1. 同步应用管理员列表到本地数据库
					wxAdminService.syncAdminList(wxCpTpService, corp);

					//2. 同步企业部门及用户列表到本地数据库
					wxDepartmentService.syncDepartments(wxCpTpService, corp, true);

					//3 需要根据业务创建的tag初始化 TODO

				}
			});


			log.info("永久授权码：" + permanentCode);
		} catch (WxErrorException e) {
			log.error("getPermanentCodeInfo err:" , e);
		}

		return null;
	}
}
